﻿Imports Microsoft.VisualBasic

Public MustInherit Class CProductPage : Inherits CSearchPage

#Region "Querystring"
    Public ReadOnly Property ProductId() As Integer
        Get
            If Page.RouteData.Values.ContainsKey("productId") Then
                Return Page.RouteData.Values("productId")
            Else
                ProductId = CWeb.RequestInt("productId")
                Dim p As CProduct = CProduct.Cache.GetById(ProductId)
                If IsNothing(p) Then Response.RedirectPermanent(CSitemap.Store)
                Response.RedirectPermanent(CSitemap.Decide(p))
            End If
        End Get
    End Property
    Public ReadOnly Property ProductName As String
        Get
            If Page.RouteData.Values.ContainsKey("productName") Then
                Return Page.RouteData.Values("productName")
            Else
                Return CConfig.SafeFriendlyName(Product.ProductName)
            End If
        End Get
    End Property
#End Region

#Region "Data"
    Public ReadOnly Property [Product]() As CProduct
        Get
            Return CProduct.Cache.GetById(ProductId)
        End Get
    End Property
#End Region

#Region "Menu"
    'Parent Menu
    Protected Overrides ReadOnly Property TypeId As SchemaMikeConnellMinistries.EProductType
        Get
            Return Product.ProductTypeId_
        End Get
    End Property

    'Set Menu
    Protected MustOverride ReadOnly Property SetPanel1 As Control
    Protected MustOverride ReadOnly Property SetPanel2 As Control
    Protected MustOverride ReadOnly Property BottomLinks As HtmlTableRow
    Protected MustOverride ReadOnly Property BottomRandom As HtmlTableRow


    'Logic
    Protected Sub SetMenuLinks(ctrl As Control, p As CProduct)
        If p.IsSet Then
            'Collection, Manuals/Sermons, Transcripts
            SetMenuLink(ctrl, p)
            For Each i As CProduct In p.Children.Active.Manuals
                SetMenuLink(ctrl, i)
            Next
            For Each i As CProduct In p.Children.Active.Sermons
                SetMenuLink(ctrl, i)
            Next
            For Each i As CProduct In p.Children.Active.Documents
                SetMenuLink(ctrl, i)
            Next
            If p.Children.HavingTranscripts.Count > 0 Then SetTranscriptLink(ctrl, p)
        ElseIf Not IsNothing(p.BelongsTo) Then
            SetMenuLinks(ctrl, p.BelongsTo)
        End If

        For Each i As Control In ctrl.Controls
            If TypeOf i Is HyperLink Then
                Dim lnk As HyperLink = i
                If lnk.CssClass = "menu" Then lnk.CssClass = String.Empty
            End If
        Next
    End Sub
    Protected Sub SetMenuLink(ctrl As Control, i As CProduct)
        If i.IsSet Then
            SetMenuLink(ctrl, "Collection", CSitemap.Decide(i), ProductId = i.ProductId, i.ProductName)
        ElseIf i.ProductTypeId_ = EProductType.Manual Then
            SetMenuLink(ctrl, "Manual", CSitemap.Decide(i), ProductId = i.ProductId, i.ProductNameAndContents)
        ElseIf Not IsNothing(i.BelongsTo) Then
            If i.ProductTypeId_ = EProductType.Document Then
                SetMenuLink(ctrl, i.BelongsTo.Children.Documents.IndexOf(i) + 1, CSitemap.Decide(i), ProductId = i.ProductId, i.ProductNameAndContents)
            Else
                SetMenuLink(ctrl, i.BelongsTo.Children.Sermons.IndexOf(i) + 1, CSitemap.Decide(i), ProductId = i.ProductId, i.ProductNameAndContents)
            End If
        End If
    End Sub
    Protected Sub SetTranscriptLink(ctrl As Control, p As CProduct)
        MenuLink(ctrl, "Transcripts&raquo;", CSitemap.Transcript(p), False, "Audio Transcripts") '.Style.Add("margin-left", "10px")
    End Sub
    Protected Function SetMenuLink(ctrl As Control, name As String, url As String, selected As Boolean, tooltip As String) As HyperLink
        Return MenuLink(ctrl, name, url, selected, tooltip)
    End Function


    Public Shared Sub NavLinks(target As Label, siblings As CProductList, p As CProduct, name As String, url As String, Optional tooltip As String = Nothing)
        If IsNothing(tooltip) Then tooltip = name
        Dim lnk As New HyperLink
        lnk.Text = name
        lnk.NavigateUrl = url
        lnk.ToolTip = tooltip
        NavLinks(target, siblings, p, lnk)
    End Sub
    Public Shared Sub NavLinks(target As Label, siblings As CProductList, p As CProduct, lnk As HyperLink)
        '77,78,79...
        If siblings.Count < 2 Then Exit Sub
        'If siblings.Count < 10 Then siblings.Reverse()

        Dim index As Integer = siblings.IndexOf(p)
        Dim min As Integer = index - 4 'left of middle
        Dim max As Integer = index + 4 'right of middle
        If index > 100 Then 'Big numbers => squish it down a bit
            min = index - 2
            max = index + 2
        End If
        'Endpoints: make adjustments
        If max >= siblings.Count Then
            max = siblings.Count - 1
            min = max - 6
            If min < 0 Then min = 0
        End If
        If min < 0 Then
            max -= min
            min = 0
            If max >= siblings.Count Then max = siblings.Count - 1
        End If


        target.Controls.Add(lnk)
        If min > 0 Then
            Dim i As CProduct = siblings(0)
            lnk = New HyperLink
            lnk.Text = (1 + siblings.IndexOf(i))
            If i.ProductTypeId_ = EProductType.Manual Then lnk.Text = CUtilities.Truncate(i.ProductName, 13).Replace("...", "…")
            lnk.NavigateUrl = CSitemap.Decide(i)
            lnk.ToolTip = String.Concat(i.DateString, ": ", i.ProductName)
            target.Controls.Add(lnk)
            Dim lit As New Literal
            lit.Text = "..."
            If min > 1 Then target.Controls.Add(lit)
        End If
        For j As Integer = min To max
            Dim i As CProduct = siblings(j)

            lnk = New HyperLink
            lnk.Text = (1 + siblings.IndexOf(i))
            If i.ProductTypeId_ = EProductType.Manual Then lnk.Text = CUtilities.Truncate(i.ProductName, 13).Replace("...", "…")
            lnk.NavigateUrl = CSitemap.Decide(i)
            lnk.ToolTip = String.Concat(i.DateString, ": ", i.ProductName)
            target.Controls.Add(lnk)
            If i.ProductId = p.ProductId Then lnk.CssClass = "selected"
        Next
        If max + 1 < siblings.Count Then
            Dim lit As New Literal
            lit.Text = "..."
            If max + 2 < siblings.Count Then target.Controls.Add(lit)

            Dim i As CProduct = siblings(siblings.Count - 1)
            lnk = New HyperLink
            lnk.Text = (1 + siblings.IndexOf(i))
            If i.ProductTypeId_ = EProductType.Manual Then lnk.Text = CUtilities.Truncate(i.ProductName, 13).Replace("...", "…")
            lnk.NavigateUrl = CSitemap.Decide(i)
            lnk.ToolTip = String.Concat(i.DateString, ": ", i.ProductName)
            target.Controls.Add(lnk)
        End If
    End Sub
#End Region

#Region "Event Handlers"
    Private Sub CProductPage_Load(sender As Object, e As System.EventArgs) Handles Me.Load
        SetMenuLinks(SetPanel1, Product)
        SetMenuLinks(SetPanel2, Product)
        BottomMenuLinks()

        SetPanel1.Visible = SetPanel1.Controls.Count > 0

        Dim meta As New HtmlMeta()
        meta.HttpEquiv = "content-language"
        If Product.ProductLanguageId = ELanguage.Chinese Then
            meta.Content = "zh-sg"
            Page.Header.Controls.Add(meta)
        ElseIf Product.ProductLanguageId = ELanguage.Hindi Then
            meta.Content = "hi"
            Page.Header.Controls.Add(meta)
        End If
    End Sub

#End Region


    Private Sub BottomMenuLinks()
        BottomMenuLinks(BottomLinks, BottomRandom, Product)
    End Sub
    Public Shared Sub BottomMenuLinks(topRow As HtmlTableRow, bottomRow As HtmlTableRow, p As CProduct)
        'Bottom menu links, plus a random selection below each
        Dim tdMan As HtmlTableCell = Nothing
        For Each i As CProductType In CProductType.Cache.PlusAll
            If i.ActiveCount = 0 Then Continue For
            If i.TypeId = EProductType.Document Then Continue For

            Dim td As New HtmlTableCell
            td.NoWrap = True

            Dim lnk As New HyperLink
            lnk.Text = i.PluralAndActive
            If i.TypeId = 0 Then lnk.Text = "Speakers"
            lnk.NavigateUrl = CSitemap.Store(i.TypeId)
            If i.TypeId = 0 Then lnk.NavigateUrl = CSitemap.StoreForSpeaker(0)
            If p.ProductTypeId_ = i.TypeId Then lnk.CssClass = "selected" Else lnk.CssClass = "menu"

            If i.TypeId = EProductType.Paperback AndAlso Not IsNothing(tdMan) Then
                Dim div As New HtmlGenericControl("div")
                div.Style.Add("margin-top", "15px")
                tdMan.Controls.Add(div)
                div.Controls.Add(lnk)
            Else
                td.Controls.Add(lnk)
                topRow.Cells.Add(td)
            End If

            If i.TypeId = EProductType.Manual Then
                tdMan = ShowSome(i, bottomRow, p)
            ElseIf i.TypeId = EProductType.Paperback AndAlso Not IsNothing(tdMan) Then
                ShowSome(i, tdMan, p)
            Else
                ShowSome(i, bottomRow, p)
            End If
        Next
    End Sub
    Private Shared Function ShowSome(type As CProductType, row As HtmlTableRow, p As CProduct) As HtmlTableCell
        Dim td As New HtmlTableCell
        td.NoWrap = True
        td.VAlign = "top"
        row.Cells.Add(td)

        ShowSome(type, td, p)
        Return td
    End Function
    Private Shared Sub ShowSome(type As CProductType, td As HtmlTableCell, selected As CProduct)

        Dim limit As Integer = 15
        If type.TypeId = EProductType.Paperback Then limit = 12

        If type.TypeId = EProductType.All Then
            'Random speakers 
            Dim randSpeak As New CSpeakerList(CShuffle.Shuffle(CSpeaker.Cache.HavingProducts))
            If randSpeak.Count > limit Then randSpeak = New CSpeakerList(randSpeak.GetRange(0, limit))

			'With most popular speakers taking the top half
			Dim bestSpeak As CSpeakerList = CSpeaker.Cache.SortByActiveCountDescName
			Dim startAt As Integer = 7
			If bestSpeak.Count <= startAt Then startAt = bestSpeak.Count - 1
			For i As Integer = startAt To 0 Step -1
				If randSpeak.Contains(bestSpeak(i)) Then randSpeak.Remove(bestSpeak(i))
				randSpeak.Insert(0, bestSpeak(i))
			Next

			Dim mc As CSpeaker = CSpeaker.Cache.GetById(ESpeaker.MikeConnell)
            If Not randSpeak.Contains(mc) Then randSpeak.Insert(0, mc)

            For i As Integer = 0 To limit
                If randSpeak.Count <= i Then Exit Sub
                Dim s As CSpeaker = randSpeak(i)

                Dim div As New HtmlGenericControl("div")
                td.Controls.Add(div)

                Dim lnk As New HyperLink
                div.Controls.Add(lnk)
                lnk.Text = s.NameAndCountActive
                lnk.ToolTip = s.SpeakerName
                lnk.NavigateUrl = CSitemap.StoreForSpeaker(s.SpeakerId)
                lnk.CssClass = "smalllinks"
                If s.SpeakerId = selected.ProductSpeakerId OrElse s.SpeakerId = selected.ProductSpeaker2Id Then RandomSelected(lnk)
            Next
            Exit Sub
        End If


        Dim shortList As New CProductList(CShuffle.Shuffle(type.Products.Active))
        If shortList.Count <= 5 Then shortList.Sort()

        For i As Integer = 0 To limit
            If shortList.Count <= i Then Exit Sub
            Dim p As CProduct = shortList(i)

            Dim div As New HtmlGenericControl("div")
            td.Controls.Add(div)

            Dim lnk As New HyperLink
            div.Controls.Add(lnk)
            lnk.Text = CUtilities.Truncate(p.ProductName, 30)
            lnk.ToolTip = p.ProductName
            lnk.NavigateUrl = CSitemap.Decide(p)
            lnk.CssClass = "smalllinks"
            If p.ProductId = selected.ProductId Then RandomSelected(lnk)
            If p.ProductTypeId = EProductType.Paperback Then
                lnk.NavigateUrl = CSitemap.External_CreateSpace(p)
                lnk.Target = "_blank"
            End If
        Next
    End Sub
    Private Shared Sub RandomSelected(lnk As HyperLink)
        lnk.Font.Underline = True
        lnk.ForeColor = Drawing.Color.Black
    End Sub
End Class
